package com.ai.platform.system.service.impl;

import com.ai.platform.common.util.AiPlatformUtil;
import com.ai.platform.common.util.ConvertUtil;
import com.ai.platform.core.constant.IConstants;
import com.ai.platform.core.exception.BusinessException;
import com.ai.platform.model.dto.Input;
import com.ai.platform.model.dto.Output;
import com.ai.platform.system.entity.SysRole;
import com.ai.platform.system.entity.SysUser;
import com.ai.platform.system.mapper.SysRoleMapper;
import com.ai.platform.system.service.ISysRoleService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author yeyingsheng
 * @since 2018-05-12
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Override
    public void queryRoleByUserId(Input input, Output output) throws BusinessException {
        Integer userId = Integer.parseInt(input.getValue("userId"));
        try {
            List<SysRole> roles = baseMapper.queryRoleByUserId(userId);
            output.setData(roles);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new BusinessException("SQL异常:" + e.getMessage());
        }
    }

    @Override
    public void listRoleAll(Input input, Output output) throws BusinessException {
        //查询所有角色
        List<SysRole> roles = baseMapper.selectList(new EntityWrapper<SysRole>().orderBy("order_no", true));
        //查询用户ID拥有角色
        String userId=input.getValue("userId");
        List<SysRole> myRoles = null;
        try {
            if(!StringUtils.isEmpty(userId)){
                myRoles = baseMapper.queryRoleByUserId(Integer.parseInt(userId));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roles)) {
            for (SysRole role : roles) {
                boolean isChecked = false;
                if (!CollectionUtils.isEmpty(myRoles)) {
                    for (SysRole myRole : myRoles) {
                        if (String.valueOf(role.getId()).equals(String.valueOf(myRole.getId()))) {
                            isChecked = true;
                            break;
                        }
                    }
                }
                Map<String, Object> map = new HashMap<>();
                map.put("id", role.getId());
                map.put("name", role.getName());
                map.put("checked", isChecked);
                resultList.add(map);
            }
        }
        output.setData(resultList);
    }

    @Override
    public void listRole(Input input, Output output) throws BusinessException {
        int limit =Integer.parseInt(input.getValue("limit"));
        //当前页
        int pageNow = Integer.valueOf(input.getValue("page"));
        EntityWrapper<SysRole> wrapper=new EntityWrapper<>();
        Page<SysRole> page = new Page(pageNow,limit);
        page.setTotal(this.selectCount(wrapper));
        page=this.selectPage(page,wrapper);
        output.setCount(page.getTotal());
        List<SysRole> userList=page.getRecords();
        output.setData(userList);
    }

    @Override
    public void saveRole(Input input, Output output) throws BusinessException {
         SysRole sysRole= ConvertUtil.mapArrayToBean(input.getInputMap(),SysRole.class);
         if(null!=sysRole.getId()){//修改
              SysRole oldRole=this.selectById(sysRole.getId());
              if(null==oldRole){
                  AiPlatformUtil.returnMsgBuild(output, IConstants.FIELD_VALID_ERROR,"角色不存在");
                  return;
              }
         }
         if(!this.insertOrUpdate(sysRole)){
             //保存或修改失败
             AiPlatformUtil.returnMsgBuild(output,IConstants.UNKNOWN_ERROR,"保存失败");
         }
        Integer id=sysRole.getId();
        String permissionIdStr=input.getValue("permissionIds");
        if(!StringUtils.isEmpty(permissionIdStr)){
            //删除角色权限资源关联
            this.baseMapper.deleteRolePermissionRelByRoleId(id);
            //权限资源ID
            String[] permissionIds = permissionIdStr.split(AiPlatformUtil.SPLIT_ID);
            List<Map<String, Integer>> mapList = new ArrayList<>();
            //保存用户角色关系
            if (null != permissionIds && permissionIds.length > 0) {
                Map<String, Integer> map;
                for (String s : permissionIds) {
                    map = new HashMap<>();
                    map.put("roleId", id);
                    map.put("permissionId", Integer.parseInt(s));
                    mapList.add(map);
                }
            }
            this.baseMapper.insertRolePermissionRelBatch(mapList);
        }
    }

    @Override
    public void deleteRole(Input input, Output output) throws BusinessException {
        String ids=input.getValue("ids");
        List<Serializable> idList= AiPlatformUtil.strToList(ids,Integer.class);
        for(Serializable id:idList) {
            this.baseMapper.deleteRolePermissionRelByRoleId((Integer) id);
            this.deleteById(id);
        }
    }
}
